package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.System;
import com.cskaoyan.bean.vo.CartCheckoutVo;
import com.cskaoyan.bean.wx.vo.CartVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    SystemMapper systemMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    CouponMapper couponMapper;

    @Override
    public CartVo index(Integer id) {
        // 获取购物车中的商品信息
        List<Cart> carts = getCarts(id);

        // 获取购物车的总计数据
        Map<String, Object> cartTotal = getCartTotal(carts);

        return new CartVo(cartTotal, carts);
    }

    private List<Cart> getCarts(Integer id) {
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(id).andDeletedEqualTo(false);
        return cartMapper.selectByExample(cartExample);
    }

    /*
        通过商品信息获取总计的信息,并且封装为 Vo
     */
    private Map<String, Object> getCartTotal(List<Cart> carts) {
        Map<String, Object> cartTotal = new HashMap<>();
        Integer goodsCount = 0;
        Integer checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal("0");
        BigDecimal checkedGoodsAmount = new BigDecimal("0");

        for (Cart cart : carts) {
            goodsCount += cart.getNumber();
            goodsAmount = goodsAmount.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber().longValue())));
            if (cart.getChecked()) {
                checkedGoodsCount += cart.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber().longValue())));
            }
        }

        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("goodsAmount", goodsAmount);
        cartTotal.put("checkedGoodsAmount", checkedGoodsAmount);
        return cartTotal;
    }

    @Override
    public CartVo checked(List<Integer> productIds, Boolean isChecked, Integer userId) {
        Cart cart = new Cart();
        cart.setChecked(isChecked);
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andProductIdIn(productIds);
        cartMapper.updateByExampleSelective(cart, cartExample);

        List<Cart> carts = getCarts(userId);
        Map<String, Object> cartTotal = getCartTotal(carts);
        return new CartVo(cartTotal, carts);
    }

    @Override
    public void update(Cart cart) {
        cart.setUpdateTime(DateUtils.getCurrentTime());
        cartMapper.updateByPrimaryKeySelective(cart);
    }

    @Override
    public CartVo delete(List<Integer> productIds, Integer userId) {
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andProductIdIn(productIds);
        Cart cart = new Cart();
        cart.setDeleted(true);
        cartMapper.updateByExampleSelective(cart, cartExample);
        CartVo cartVo = index(userId);
        return cartVo;
    }

    @Override
    public Integer add(Cart cart, Integer userId) {
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andGoodsIdEqualTo(cart.getGoodsId()).andProductIdEqualTo(cart.getProductId()).andDeletedEqualTo(false).andUserIdEqualTo(userId);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        if (carts != null && carts.size() != 0) {
            cartMapper.updateNumber(cart.getNumber(), cart.getGoodsId(), cart.getProductId());
        } else {
            addGoodsToCart(cart);
        }
        return goodscount(cart.getUserId());
    }

    // 向购物车表中插入一条数据
    private void addGoodsToCart(Cart cart) {
        Goods goods = goodsMapper.selectByPrimaryKey(cart.getGoodsId());
        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(cart.getProductId());
        cart.setGoodsSn(cart.getGoodsId().toString());
        cart.setGoodsName(goods.getName());
        cart.setPrice(goodsProduct.getPrice());
        cart.setSpecifications(goodsProduct.getSpecifications());
        cart.setPicUrl(goods.getPicUrl());
        cart.setAddTime(DateUtils.getCurrentTime());
        cart.setUpdateTime(DateUtils.getCurrentTime());
        cartMapper.insertSelective(cart);
    }

    // 利用 userId 获取到购物车中商品的数量
    public Integer goodscount(Integer userId) {
        Integer count = cartMapper.selectCartNumberTotal(userId);
        return count;
    }

    /*
        立即购买，首先要将该商品添加到购物车
     */
    @Override
    public Integer fastAdd(Cart cart) {

        addGoodsToCart(cart);
        return cart.getId();
    }

    @Override
    public CartCheckoutVo checkout(Integer cartId, Integer addressId, Integer couponId, Integer grouponRulesId, Integer userId) {
        CartCheckoutVo cartCheckoutVo = new CartCheckoutVo();
        // 获取地址信息
        Address checkedAddress = new Address();
        if (addressId == 0) {
            checkedAddress.setId(0);
        } else {
            // 如果请求参数不为 0, 则利用addressId查找
            checkedAddress = addressMapper.selectByPrimaryKey(addressId);
        }

        BigDecimal goodsTotalPrice = BigDecimal.ZERO;
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andCheckedEqualTo(true).andDeletedEqualTo(false).andUserIdEqualTo(userId);
        // 获取商品信息
        List<Cart> carts = new ArrayList<>();
        if (cartId == 0) {
            carts = cartMapper.selectByExample(cartExample);
        } else {
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            carts.add(cart);
        }

        // 求商品总金额
        for (Cart cart : carts) {
            goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber().longValue())));
        }

        // 实际应付金额
        Integer actualPrice = 0;

        String value = "cskaoyan_mall_express_freight_value";
        String min = "cskaoyan_mall_express_freight_min";
        Integer freightValue = getSystemValue(value);
        Integer freightMin = getSystemValue(min);
        // 如果商品总金额小最低包邮的条件，则增加邮费
        actualPrice += goodsTotalPrice.intValue();
        if (goodsTotalPrice.intValue() < freightMin) {
            actualPrice += freightValue;
            cartCheckoutVo.setFreightPrice(freightValue);
        } else {
            cartCheckoutVo.setFreightPrice(0);
        }


        // 如果请求参数中的couponId为0则找最大值
        // 如果不为0, 则根据couponId找出对应的优惠券
         /*
            -1   price 0                length 可用张数
            0    price max              length 可用张数
            >0   price 优惠券对应的price length 1
         */
        Coupon couponTemp = null;
        Integer size = 0;
        List<Coupon> coupons = couponMapper.selectCouponInfo(goodsTotalPrice.intValue(), userId);
        if (coupons == null || coupons.size() == 0) {
            cartCheckoutVo.setCouponId(0);
            cartCheckoutVo.setCouponPrice(0);
        } else {
            if (couponId > 0) {
                couponTemp = couponMapper.selectByPrimaryKey(couponId);
                actualPrice -= couponTemp.getDiscount().intValue();
                cartCheckoutVo.setCouponPrice(couponTemp.getDiscount().intValue());
                size = 1;
            } else if (couponId == 0) {
                couponTemp.setDiscount(BigDecimal.ZERO);
                size = coupons.size();
                couponTemp = getDiscountMaxByCouponInfo(coupons, couponTemp);
                actualPrice -= couponTemp.getDiscount().intValue();
                cartCheckoutVo.setCouponPrice(couponTemp.getDiscount().intValue());

            } else if (couponId == -1) {
                size = coupons.size();
                cartCheckoutVo.setCouponPrice(0);
            }
        }

//        // 请求参数couponId为0. 查询用户的可用优惠券数据
//        if (couponTemp != null) {
//            if (coupons != null && coupons.size() != 0) {
//                coupons.get(0);
//                couponTemp = getDiscountMaxByCouponInfo(coupons, couponTemp);
//                size = coupons.size();
//            }
//        }
//        if (couponTemp != null) {
//            cartCheckoutVo.setCouponId(couponTemp.getId());
//            cartCheckoutVo.setCouponPrice(couponTemp.getDiscount().intValue());
//        } else {
//            cartCheckoutVo.setCouponId(0);
//            cartCheckoutVo.setCouponPrice(0);
//        }

        cartCheckoutVo.setGrouponRulesId(0);
        cartCheckoutVo.setGrouponPrice(0);
        cartCheckoutVo.setCheckedAddress(checkedAddress);
        cartCheckoutVo.setActualPrice(actualPrice);
        cartCheckoutVo.setOrderTotalPrice(actualPrice);

        cartCheckoutVo.setAvailableCouponLength(size);

        cartCheckoutVo.setCheckedGoodsList(carts);
        cartCheckoutVo.setGoodsTotalPrice(goodsTotalPrice);
        cartCheckoutVo.setAddressId(checkedAddress.getId());

        return cartCheckoutVo;
    }

    private Coupon getDiscountMaxByCouponInfo(List<Coupon> coupons, Coupon couponTemp) {
        for (Coupon coupon : coupons) {
            if (couponTemp.getDiscount().intValue() < coupon.getDiscount().intValue()) {
                couponTemp = coupon;
            }
        }
        return couponTemp;
    }

    private Integer getSystemValue(String keyname) {
        SystemExample example = new SystemExample();
        example.createCriteria().andKeyNameEqualTo(keyname);
        List<System> valueList = systemMapper.selectByExample(example);
        return Integer.parseInt(valueList.get(0).getKeyValue());
    }

}
